//
//  TJComposeVewController.swift
//  TJSinaWeibo
//
//  Created by 唐后能 on 16/4/18.
//  Copyright © 2016年 itheima. All rights reserved.
//

import UIKit
import SVProgressHUD

private let maxOfLength = 25

class TJComposeVewController: UIViewController {

    // 记录图片选择器是否显示.
    private var isShowPhotoSelecteVC:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 设置UI.
        setupUI()
        
        // 注册通知,监听键盘frame的改变.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("KeyboardWillChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 一加载就让textVeiw成为第一响应者.放在此处处理toolBar会有奇怪的动画.-->要放到viewDidAppear中
//        textView.becomeFirstResponder()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        // 当图片选择器隐藏时,才显示键盘(成为第一响应者)
        if !isShowPhotoSelecteVC {
        
            textView.becomeFirstResponder()
        }
    }
    
    // 移除通知.
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // 通知的监听方法.
    @objc private func KeyboardWillChangeFrame(notice:NSNotification) {
    
//        TJPrint("\(notice)")
        // 获取键盘结束时候的frame.
        let frame = notice.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        // 获取键盘弹出的时间.
        let duration = notice.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        // 计算toolBar的底部约束.
        let toolBarBottonConstrains = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        
        // 更新toolBar的底部约束,让它跟随键盘移动.
        self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(self.view).offset(toolBarBottonConstrains)
        })
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded() //让view重新布局子控件.
        }
    }
    
    // 设置UI.
    private func setupUI () {
    
        // 设置导航栏.
        setupNav()
        
        // 设置TextView
        setupTextView ()
        
        // 添加照片选择器控制器的View.
        setupPhotoSelect()
        
        // 设置setupToolBar
        setupToolBar ()
        
        // 设置提示label.
        setupTipLabel()
    }
    
    // 设置图片选择器.
    private func setupPhotoSelect(){
    
        // 1,添加控件.
        view.addSubview(photoSelectVC.view)
        // 注意控制器的View互为父子关系,控制器也必须互为父子关系.
        self.addChildViewController(photoSelectVC)
        
        // 2,添加约束.
        photoSelectVC.view.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(UIScreen.mainScreen().bounds.height*0.6)
            make.height.equalTo(UIScreen.mainScreen().bounds.height*0.6)
        }
        
    }
    
    // 设置提示label.
    private func setupTipLabel(){
    
        view.addSubview(lengthTipLabel)
        lengthTipLabel.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(toolBar).offset(-TJStatusCellMargin)
            make.bottom.equalTo(toolBar.snp_top).offset(-TJStatusCellMargin)
        }
    }
    
    // 设置toolBar.
    private func setupToolBar () {
    
        // 1,添加到父控件中.
        view.addSubview(toolBar)
        
        // 2,设置约束.
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
    }
    
    // 设置TextView.
    private func setupTextView () {
    
        // 1,添加子控件.
        view.addSubview(textView)
        // 2,添加约束.
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self.view) // 默认自动适应scrollView的insert.
        }
    }
    
    // 设置导航栏.
    private func setupNav(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancelBtnClicked"))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("sendBtnClicked"))
        // 一开始禁用发送按钮.
        navigationItem.rightBarButtonItem?.enabled = false
        // 设置标题.
        setupTitleView()
    }
    // 设置标题.
    private func setupTitleView(){
    
        // 获取账号名称.
        let prifix = "发微博"
        if let name = TJAccountViewModel.shareUserAccount.userAccount?.screen_name {
        
            let title = prifix + "\n" + name
        
            // 创建label.
            let label = UILabel(fontSize: 18, contentColor: UIColor.blackColor())
            // 设置其它属性.
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            
            // 使用属性文本给titleView赋值.
            let attrString = NSMutableAttributedString(string: title)
            // 给某些字符设置特殊属性.
            let range = (title as NSString).rangeOfString(name)
        attrString.addAttributes([NSForegroundColorAttributeName:UIColor.lightGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(14)], range:range)
            
            label.attributedText = attrString
            // 设置大小.如果没有设置,不会显示.
            label.sizeToFit()
            navigationItem.titleView = label
        }else { //没有账号名.
        
            navigationItem.title = prifix
        }
    }
    
    // MARK - 导航栏按钮点击事件.
    // 取消.
    @objc func cancelBtnClicked(){
        // textView取消第一相应者,键盘就会退下
        textView.resignFirstResponder()
        // 隐藏提示.
        SVProgressHUD.dismiss()
        // 关闭控制器.
        dismissViewControllerAnimated(true, completion: nil)
    }
    // 取消.
    @objc func sendBtnClicked(){
//        TJPrint("点击了发送按钮")
        
        // 判断输入内容是否在规定字数内.
        if textView.emoticonText().characters.count > maxOfLength {
        
            SVProgressHUD.showErrorWithStatus("发布的内容超出上限!")
            return
        }
        
        // 获取照片选择器数组中的第一张图片.
        let image = photoSelectVC.photos.first
        
        // 提示正在发送.
        SVProgressHUD.showWithStatus("正在发送...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.Black)
        
        TJStatusViewModel.shareStatusManager.sendStatus(textView.emoticonText(),image: image) { (error) -> () in
            if error != nil {
            
                TJPrint("微博发布失败:\(error)")
                SVProgressHUD.showErrorWithStatus("发布失败!")
            }
            
            // 发布微博成功.
            SVProgressHUD.showSuccessWithStatus("发布成功")
            
            // 1s后关闭,并跳转到主页.
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                // 发布微博成功了, 关闭控制器
                self.cancelBtnClicked()
            })
        }
    }
    
    // toolBar上item的点击事件.
    // 表情
    @objc func emoticon(button:UIButton){
//        TJPrint("点击表情")
        
        // 先让键盘退下.
        textView.resignFirstResponder()
        
        // 进行键盘的切换.
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        // 定义键盘切换按钮的图片.
        var normalImage: UIImage?
        var highlightedImage: UIImage?
        if textView.inputView == nil {
            // 系统键盘
            normalImage = UIImage(named: "compose_emoticonbutton_background")
            highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        } else {
            // 自定义键盘
            normalImage = UIImage(named: "compose_keyboardbutton_background")
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        button.setImage(normalImage, forState: UIControlState.Normal)
        button.setImage(highlightedImage, forState: UIControlState.Highlighted)
        
        // 等0.25s后,让键盘再弹出来.
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
        
    }
    // 图片.
    @objc func picture(){
        TJPrint("图片")
        // 让控制图片选择器显示的bool值取反.
        self.isShowPhotoSelecteVC = !isShowPhotoSelecteVC
        if isShowPhotoSelecteVC == true {
        
            photoSelectVC.view.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view)
            }
            UIView.animateWithDuration(0.25) { () -> Void in
                self.view.layoutIfNeeded()
                // 退下图片选择器,让键盘辞去第一响应者
                self.textView.becomeFirstResponder()
            }
        }else {
        
            photoSelectVC.view.snp_updateConstraints { (make) -> Void in
                make.bottom.equalTo(self.view).offset(UIScreen.mainScreen().bounds.height*0.6)
            }
            UIView.animateWithDuration(0.25) { () -> Void in
                self.view.layoutIfNeeded()
                // 隐藏图片选择器,让键盘成为第一响应者
                self.textView.becomeFirstResponder()
            }
        }
        
            }
    @objc func mention(){
        TJPrint("@")
    }
    @objc func trend(){
        TJPrint("#")
    }
    @objc func add(){
        TJPrint("添加")
    }

    
    
    // MARK: - 懒加载.
    // textView.
    private lazy var textView:TJTextView = {
    
        let tv:TJTextView = TJTextView()
        // 设置.
        tv.placeholder = "我是占位文本..."
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.blackColor()
        tv.delegate = self
        // 设置垂直滚动效果.-->不设置的话,textView不能滚动.
        tv.alwaysBounceVertical = true
        
        // 设置tv键盘的消失模式:滚动tv的时候消失
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
    }()
    
    // toolBar.
    private lazy var toolBar:UIToolbar = {
    
        let bar = UIToolbar()
        // 设置子控件.
        // 每个item对应的图片名称,点击事件的方法名称放入字典数组中.
        let itemSettings = [
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_add_background", "action": "add"]
        ]
        
        // 遍历字典数组,创建barButtonItem
        var items = [UIBarButtonItem]()
        for dict in itemSettings {
            
            // 拿到图片名称和对应的方法名称
            let imgName = dict["imageName"]
            let actionName = dict["action"]
            // 创建对应的barButtonItem.
            let item:UIBarButtonItem = UIBarButtonItem(imgName: imgName!, hightImgName: nil,target: self, action: Selector(actionName!))
            let spring = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            // 添加到item数组中.
            items.append(item)
            // 添加一个弹簧.
            items.append(spring)
        }
        // 删除最后一个元素,多了一个弹簧.
        items.removeLast()
        
        // 将items数组赋值给bar的items属性.
        bar.items = items
        
        return bar
    }()
    
    // 表情键盘的view
    private lazy var emoticonKeyboard: TJEmotionKeyBoard = {
        let keyboard = TJEmotionKeyBoard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    // 长度提示label
    private lazy var lengthTipLabel: UILabel = {
        let label = UILabel(fontSize: 10, contentColor: UIColor.lightGrayColor())
        
        label.text = String(maxOfLength)
        label.sizeToFit()
        
        return label
    }()
    
    // 图片选择控制器.
    private lazy var photoSelectVC:TJPhotoSelectorController = TJPhotoSelectorController()
}


// MARK: - textVeiw文字改变的监听.-->表情文本的改变系统不会发通知.
extension TJComposeVewController: UITextViewDelegate {
    // 文字改变
    func textViewDidChange(textView: UITextView) {
        // 设置导航栏右边按钮的可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        // 已经输入文本
        let text = textView.emoticonText()
        
        // 计算剩余文本的长度
        let last = maxOfLength - text.characters.count
        
        lengthTipLabel.text = String(last)
        
        let color = last < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        lengthTipLabel.textColor = color
    }
}


